// src/services/api.js - 简化的HTTP API服务
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://172.16.1.254:8000'

// 通用请求方法
async function request(url, options = {}) {
    const token = localStorage.getItem('auth_token')

    const response = await fetch(`${API_BASE_URL}${url}`, {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token ? `Bearer ${token}` : '',
            ...options.headers
        }
    })

    if (response.status === 401) {
        localStorage.removeItem('auth_token')
        window.location.href = '/login'
        throw new Error('Unauthorized')
    }

    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
    }

    return response.json()
}

// 角色相关
export async function getCharacters() {
    const response = await request('/api/v1/characters')
    return response.items || response || []
}

export async function selectCharacter(characterName) {
    const characters = await getCharacters()
    const character = characters.find(c => c.name === characterName)

    if (!character) {
        throw new Error('角色不存在')
    }

    const conversation = await request(`/api/v1/chat/conversations/${character.id}`, {
        method: 'POST'
    })

    return { character, conversation }
}

// 聊天历史
export async function getChatHistory() {
    try {
        const conversations = await request('/api/v1/chat/conversations')

        const sessions = await Promise.all(
            conversations.map(async (conv) => {
                const messages = await request(`/api/v1/chat/conversations/${conv.id}/messages`)
                return {
                    id: `session_${conv.id}`,
                    title: `与${conv.character?.name || '未知角色'}的对话`,
                    character: conv.character?.name,
                    startTime: conv.created_at,
                    messageCount: messages.length,
                    messages: messages.map(msg => ({
                        id: `msg_${msg.id}`,
                        content: msg.content,
                        type: msg.role === 'user' ? 'user' : 'assistant',
                        audioUrl: msg.audio_url,
                        timestamp: msg.created_at
                    }))
                }
            })
        )

        return sessions
    } catch (error) {
        console.error('获取聊天历史失败:', error)
        return []
    }
}

// 删除会话
export async function deleteConversation(sessionId) {
    const conversationId = sessionId.replace('session_', '')
    return request(`/api/v1/chat/conversations/${conversationId}`, {
        method: 'DELETE'
    })
}

// 角色管理
export async function getMyCharacters() {
    return request('/api/v1/characters/my')
}

export async function createCharacter(data) {
    // 确保数据符合API schema
    const characterData = {
        name: data.name,
        description: data.description,
        prompt_template: data.prompt_template,
        voice_id: data.voice_id || 'zh-CN-XiaoxiaoNeural',
        use_knowledge_base: data.use_knowledge_base || false,
        knowledge_search_k: data.knowledge_search_k || 3,
        tts_engine: data.tts_engine || 'edge_tts',
        settings: data.settings || {},
        tts_config: data.tts_config || {}
    }
    
    // 只在编辑模式时包含is_public，因为API的create schema中没有这个字段
    if (data.avatar_url) {
        characterData.avatar_url = data.avatar_url
    }
    
    return request('/api/v1/characters/', {
        method: 'POST',
        body: JSON.stringify(characterData)
    })
}

export async function updateCharacter(id, data) {
    // 确保数据符合API schema
    const characterData = {
        name: data.name,
        description: data.description,
        prompt_template: data.prompt_template,
        voice_id: data.voice_id,
        use_knowledge_base: data.use_knowledge_base,
        knowledge_search_k: data.knowledge_search_k,
        tts_engine: data.tts_engine,
        is_public: data.is_public,
        settings: data.settings || {},
        tts_config: data.tts_config || {}
    }
    
    if (data.avatar_url) {
        characterData.avatar_url = data.avatar_url
    }
    
    return request(`/api/v1/characters/${id}`, {
        method: 'PUT',
        body: JSON.stringify(characterData)
    })
}

export async function deleteCharacter(id) {
    return request(`/api/v1/characters/${id}`, {
        method: 'DELETE'
    })
}

export async function cloneCharacter(id, newName) {
    const url = newName
        ? `/api/v1/characters/${id}/clone?new_name=${encodeURIComponent(newName)}`
        : `/api/v1/characters/${id}/clone`
    return request(url, { method: 'POST' })
}

export async function toggleCharacterVisibility(id, isPublic) {
    return request(`/api/v1/characters/${id}/toggle-visibility?is_public=${isPublic}`, {
        method: 'POST'
    })
}

// 文件上传类API
export async function uploadCharacterAvatar(characterId, file) {
    const formData = new FormData()
    formData.append('file', file)

    const token = localStorage.getItem('auth_token')
    const response = await fetch(`${API_BASE_URL}/api/v1/characters/${characterId}/avatar`, {
        method: 'POST',
        headers: {
            'Authorization': token ? `Bearer ${token}` : ''
        },
        body: formData
    })

    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
    }

    return response.json()
}

export async function uploadVoiceSample(characterId, file) {
    const formData = new FormData()
    formData.append('file', file)

    const token = localStorage.getItem('auth_token')
    const response = await fetch(`${API_BASE_URL}/api/v1/characters/${characterId}/voice-sample`, {
        method: 'POST',
        headers: {
            'Authorization': token ? `Bearer ${token}` : ''
        },
        body: formData
    })

    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
    }

    return response.json()
}

// 知识库管理
export async function uploadKnowledgeDocument(file, description = '', isPublic = true) {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('description', description)
    formData.append('is_public', isPublic)

    const token = localStorage.getItem('auth_token')
    const response = await fetch(`${API_BASE_URL}/api/v1/knowledge/upload`, {
        method: 'POST',
        headers: {
            'Authorization': token ? `Bearer ${token}` : ''
        },
        body: formData
    })

    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`)
    }

    return response.json()
}

export async function getMyKnowledgeDocuments() {
    return request('/api/v1/knowledge/my')
}

export async function getPublicKnowledgeDocuments(skip = 0, limit = 20) {
    return request(`/api/v1/knowledge/public?skip=${skip}&limit=${limit}`)
}

export async function getCharacterKnowledgeDocuments(characterId) {
    return request(`/api/v1/knowledge/characters/${characterId}/documents`)
}

export async function linkKnowledgeToCharacter(characterId, documentId) {
    return request(`/api/v1/knowledge/characters/${characterId}/link/${documentId}`, {
        method: 'POST'
    })
}

export async function unlinkKnowledgeFromCharacter(characterId, documentId) {
    return request(`/api/v1/knowledge/characters/${characterId}/unlink/${documentId}`, {
        method: 'DELETE'
    })
}

export async function deleteKnowledgeDocument(documentId) {
    return request(`/api/v1/knowledge/documents/${documentId}`, {
        method: 'DELETE'
    })
}

export async function updateKnowledgeDocumentVisibility(documentId, isPublic) {
    return request(`/api/v1/knowledge/documents/${documentId}/visibility?is_public=${isPublic}`, {
        method: 'PUT'
    })
}